import * as Cesium from 'cesium'
Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2NjhmZWI2My02YmZhLTQxNWMtOTUwZS1jMDRlMzcwZDY3NTUiLCJpZCI6MTYwNTEyLCJpYXQiOjE2OTIwODgzODV9.cH-_wLy30r2BahkozYpNMyLSSiiieEAc1zg9KOK88Qo'
/**
 * Cesium地图初始化工具类
 */
class CesiumInitializer {
  /**
   * 初始化Cesium地图
   * @param {string} containerId - 地图容器ID
   * @param {Object} options - 初始化配置选项
   * @returns {Cesium.Viewer} Cesium viewer实例
   */
  static async init(containerId, options = {}) {
    // 从config.json加载配置
    const response = await fetch('./config.json')
    const configData = await response.json()

    // 设置Cesium Ion访问令牌
    // Cesium.Ion.defaultAccessToken = configData.ionToken
    Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2NjhmZWI2My02YmZhLTQxNWMtOTUwZS1jMDRlMzcwZDY3NTUiLCJpZCI6MTYwNTEyLCJpYXQiOjE2OTIwODgzODV9.cH-_wLy30r2BahkozYpNMyLSSiiieEAc1zg9KOK88Qo'

    // 默认配置
    const defaultOptions = {
      // 台湾海峡坐标作为默认初始位置
      initialPosition: {
        longitude: 119.301208,
        latitude: 24.632000,
        height: 600000
      },
      // 默认视角
      initialOrientation: {
        heading: 0.0, // 正北方向
        pitch: -Cesium.Math.PI_OVER_TWO, // 垂直向下
        roll: 0.0,
      },
      // 是否显示默认图层
      showBaseLayer: true,
      // 是否添加高德卫星图层
      addAmapLayer: true
    }

    // 合并配置
    const config = { ...defaultOptions, ...options }


    // 创建viewer实例
    const viewer = new Cesium.Viewer(containerId, {
      homeButton: false,
      geocoder: false,
      fullscreenButton: false,
      infoBox: false,
      sceneModePicker: false,
      navigationInstructionsInitiallyVisible: false,
      navigationHelpButton: false,
      orderIndependentTranslucency: false,
      shouldAnimate: false,
      scene3DOnly: false,
      selectionIndicator: false,
      baseLayerPicker: false,
      animation: true,   // 动画小组件   
      vrButton: false,    // VR模式  
      timeline: true,    // 时间轴
      // imageryProvider: false,
      contextOptions: {  // 添加contextOptions以优化Canvas2D性能
        willReadFrequently: true
      },

      // terrainProvider: new Cesium.CesiumTerrainProvider({
      //   url: configData.terrain.url,
      //   requestWaterMask: configData.terrain.requestWaterMask,
      //   requestVertexNormals: configData.terrain.requestVertexNormals
      // })
    })

    viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
      url: configData.imageryProviders.tilesLayer.url,
      minimumLevel: configData.imageryProviders.tilesLayer.minimumLevel,
      maximumLevel: configData.imageryProviders.tilesLayer.maximumLevel,
      tilingScheme: new Cesium.GeographicTilingScheme(),
      // 移除了未定义的urlFunction
      isTms: true
    }));



    // 隐藏Cesium logo
    this.hideLogo(viewer)

    // 设置初始视图范围
    this.setDefaultViewRectangle(viewer)

    // 设置初始位置
    this.setInitialPosition(viewer, config.initialPosition, config.initialOrientation)

    return viewer
  }
  /**
   * 隐藏Cesium logo和版权信息
   * @param {Cesium.Viewer} viewer - Cesium viewer实例
   */
  static hideLogo(viewer) {
    viewer.cesiumWidget.creditContainer.style.display = 'none'
  }

  /**
   * 设置默认视图范围（中国区域）
   * @param {Cesium.Viewer} viewer - Cesium viewer实例
   */
  static setDefaultViewRectangle(viewer) {
    Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(73, 18, 135, 53)
  }

  /**
   * 设置初始位置
   * @param {Cesium.Viewer} viewer - Cesium viewer实例
   * @param {Object} position - 位置信息 {longitude, latitude, height}
   * @param {Object} orientation - 视角信息 {heading, pitch, roll}
   */
  // static setInitialPosition(viewer, position, orientation) {
  //   viewer.camera.setView({
  //     destination: Cesium.Cartesian3.fromDegrees(
  //       position.longitude,
  //       position.latitude,
  //       position.height
  //     ),
  //     orientation: {
  //       heading: Cesium.Math.toRadians(orientation.heading),
  //       pitch: Cesium.Math.toRadians(orientation.pitch),
  //       roll: Cesium.Math.toRadians(orientation.roll)
  //     }
  //   })
  // }

  static setInitialPosition(viewer, position, orientation) {
    // viewer.camera.flyTo({
    //   destination: Cesium.Cartesian3.fromDegrees(
    //     position.longitude,
    //     position.latitude,
    //     position.height
    //   ),
    //   orientation: {
    //     heading: orientation.heading,
    //     pitch: orientation.pitch,
    //     roll: orientation.roll
    //   },
    //   duration: 3.0, // 飞行时间（秒）
    //   // complete: function () {
    //   //   // 飞行完成后的回调函数
    //   //   console.log('Camera flight completed');
    //   // }
    // });
    // viewer.camera.flyTo({
    //   destination: Cesium.Rectangle.fromDegrees(
    //     115.93872070312500, 21.85130210558968,
    //     122.14050292968750, 25.78010711842224
    //   ),
    //   duration: 0.5 // 飞行时间，单位秒
    // });
  }
}

export default CesiumInitializer
